const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.get('/html', (req, res) => {
  res.sendFile(__dirname+'/index.html')
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

//websocket
// 导入WebSocket模块:
const WebSocket = require('ws');

// 引用Server类:
const WebSocketServer = WebSocket.Server;

// 实例化:
const wss = new WebSocketServer({
    port: 5000
});
let globalWs = null;
wss.on('connection', function (ws) {
  console.log(`[SERVER] connection()`);
  globalWs = ws;
  globalWs.on('message', function (message) {


    let now = Date.now()
    let msg = now+':我是服务器，收到你的信息：'+message
      console.log(`[SERVER] Received: ${message}`);
    // 分析信息
    let data=message;
    if(message.includes('{')){
      // 证明是对象
      data = JSON.parse(message)
      if(data && data.status==0){
        // 不用向客户端发信息了
        console.log('server:',data)
      }
    } else {
      globalWs.send(msg, (err) => {
        if (err) {
            console.log(`[SERVER] error: ${err}`);
        }
      });
    }
    
    
      
  })
});


var count = 1;
let timer = setInterval(()=>{
  // 大于3次就不发了
  if(count>3){
    clearInterval(timer)
  }
  if(globalWs){
      // 10s后给客户端推送一个消息
    let msg = '服务器：计算完毕'+Date.now()
    globalWs.send(msg);

    count++
  }
}, 5000)